package com.yy.redisCache.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class RedisConfig {
    /**
     * 配置缓存管理器
     * @param factory 线程连接工厂
     * @return 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //设置缓存过期时间5分钟
        config.entryTtl(Duration.ofMinutes(5))
                //设置缓存前缀
                .prefixCacheNameWith("redis:cache:")
                //禁止缓存null值
                .disableCachingNullValues()
                //添加键值序列化配置
                .serializeKeysWith(keyPair())
                .serializeValuesWith(valuePair());
        
        return RedisCacheManager.builder(factory)
                .withCacheConfiguration("test",config)
                .build();
    }

    /**
     * 配置键序列化
     * @return
     */
    @Bean
    RedisSerializationContext.SerializationPair<String> keyPair(){
        return RedisSerializationContext.SerializationPair.fromSerializer( new StringRedisSerializer());
    }

    /**
     * 配置值序列化
     * @return
     */
    @Bean
    RedisSerializationContext.SerializationPair<Object> valuePair(){
        return RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer());
    }
}
